using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Linq;

namespace StarSkipGame
{
    /// <summary>
    /// 游戏状态枚举
    /// </summary>
    public enum GameState
    {
        Menu,       // 主菜单
        Playing,    // 游戏中
        GameOver,   // 游戏结束
        Paused      // 暂停
    }
    
    /// <summary>
    /// 游戏引擎类，管理整个游戏逻辑
    /// </summary>
    public class GameEngine : IDisposable
    {
        // 游戏状态
        public GameState CurrentState { get; private set; }
        
        // 游戏对象
        public Player Player { get; private set; }
        public List<Asteroid> Asteroids { get; private set; }
        
        // 游戏数据
        public float GameTime { get; private set; } // 游戏时间（秒）
        public float Difficulty { get; private set; } // 难度系数（0-1）
        public int AsteroidsAvoided { get; private set; } // 躲避的陨石数量
        public int TotalEnemiesSpawned { get; private set; } // 总共生成的敌人数量
        public int GamesPlayed { get; private set; } // 游戏次数
        
        // 演示模式
        public bool IsDemoMode { get; private set; }
        private float demoModeTimer = 0;
        private float demoModeDuration = 30.0f;
        private Random demoRandom = new Random();
        private float lastDemoDirectionChange = 0;
        private float demoDirectionChangeInterval = 0.5f; // 演示模式方向改变间隔
        
        // 游戏循环
        private Timer gameTimer;
        private DateTime lastUpdateTime;
        private float accumulator = 0; // 时间累加器
        private const float FIXED_TIMESTEP = 1.0f / 60.0f; // 固定时间步长 (60 FPS)
        private const float MAX_FRAME_TIME = 0.25f; // 最大帧时间 (防止螺旋死亡)
        
        // 陨石生成
        private float asteroidSpawnTimer = 0;
        private float asteroidSpawnInterval = 3.0f; // 初始生成间隔（秒）
        private float lastBossSpawnTime = 0; // 上次Boss生成时间
        
        // 陨石对象池和分批生成
        private List<Asteroid> asteroidPool = new List<Asteroid>();
        private Queue<AsteroidSpawnRequest> spawnQueue = new Queue<AsteroidSpawnRequest>();
        private const int ASTEROID_POOL_SIZE = 50; // 对象池大小
        private const int MAX_SPAWNS_PER_FRAME = 2; // 每帧最大生成数量
        
        // 陨石生成请求类
        private class AsteroidSpawnRequest
        {
            public int ScreenWidth { get; set; }
            public int ScreenHeight { get; set; }
            public float Difficulty { get; set; }
            public bool IsBoss { get; set; }
        }
        
        // 屏幕尺寸
        public int ScreenWidth { get; private set; }
        public int ScreenHeight { get; private set; }
        
        // 星空背景缓存
        private Point[] starPositions;
        private int[] starSizes;
        private bool starfieldInitialized = false;
        
        // 性能监控
        private int frameCount = 0;
        private float frameTimer = 0;
        private float currentFPS = 0;
        private float averageFrameTime = 0;
        private const float FPS_UPDATE_INTERVAL = 1.0f; // 每秒更新一次FPS
        
        public float CurrentFPS => currentFPS;
        public float AverageFrameTime => averageFrameTime;
        
                    // 缓存的绘图对象
        private SolidBrush whiteBrush;
        private SolidBrush blackBrush;
        private SolidBrush redBrush;
        private SolidBrush yellowBrush;
        private Font uiFont;
        private Font titleFont;
        private Font infoFont;
        private Font pauseFont;
        private Font menuFont;
        private StringFormat centerFormat;
        private bool objectsInitialized = false;
        
        // 系统管理器
        public SoundManager SoundManager { get; private set; }
        public HighScoreManager HighScoreManager { get; private set; }
        public ParticleSystem ParticleSystem { get; private set; }
        public GameModeManager GameModeManager { get; private set; }
        public AchievementSystem AchievementSystem { get; private set; }
        
        // 事件
        public event Action<GameState> GameStateChanged;
        public event Action<float> GameTimeUpdated;
        public event Action GameOver;
        public event Action<Achievement> AchievementUnlocked;
        public event Action RenderRequested; // 新增渲染请求事件
        public event Action DemoRestartRequested; // 新增演示重启请求事件
        
        // Windows API for BitBlt
        [DllImport("gdi32.dll")]
        private static extern bool BitBlt(IntPtr hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, 
            IntPtr hdcSrc, int nXSrc, int nYSrc, uint dwRop);
        
        [DllImport("gdi32.dll")]
        private static extern IntPtr CreateCompatibleDC(IntPtr hdc);
        
        [DllImport("gdi32.dll")]
        private static extern IntPtr CreateCompatibleBitmap(IntPtr hdc, int nWidth, int nHeight);
        
        [DllImport("gdi32.dll")]
        private static extern IntPtr SelectObject(IntPtr hdc, IntPtr hgdiobj);
        
        [DllImport("gdi32.dll")]
        private static extern bool DeleteObject(IntPtr hObject);
        
        [DllImport("gdi32.dll")]
        private static extern bool DeleteDC(IntPtr hdc);
        
        private const uint SRCCOPY = 0x00CC0020;
        
        // 离屏渲染缓冲区
        private Bitmap offscreenBitmap;
        private Graphics offscreenGraphics;
        private IntPtr offscreenDC;
        private IntPtr offscreenBitmapHandle;
        private bool offscreenInitialized = false;
        
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="screenWidth">屏幕宽度</param>
        /// <param name="screenHeight">屏幕高度</param>
        public GameEngine(int screenWidth, int screenHeight)
        {
            ScreenWidth = screenWidth;
            ScreenHeight = screenHeight;
            
            // 初始化游戏对象
            Asteroids = new List<Asteroid>();
            
            // 设置初始状态
            CurrentState = GameState.Menu;
            
            // 初始化系统
            InitializeSystems();
            InitializeGame();
        }
        
        /// <summary>
        /// 初始化系统
        /// </summary>
        private void InitializeSystems()
        {
            // 初始化各个系统
            SoundManager = new SoundManager();
            HighScoreManager = new HighScoreManager();
            ParticleSystem = new ParticleSystem();
            GameModeManager = new GameModeManager();
            AchievementSystem = new AchievementSystem();
            
            // 订阅成就解锁事件
            AchievementSystem.AchievementUnlocked += OnAchievementUnlocked;
        }
        
        /// <summary>
        /// 初始化缓存的绘图对象
        /// </summary>
        private void InitializeCachedObjects()
        {
            if (objectsInitialized) return;
            
            whiteBrush = new SolidBrush(Color.White);
            blackBrush = new SolidBrush(Color.Black);
            redBrush = new SolidBrush(Color.Red);
            yellowBrush = new SolidBrush(Color.Yellow);
            
            uiFont = new Font("Arial", 12, FontStyle.Regular);
            titleFont = new Font("Arial", 24, FontStyle.Bold);
            infoFont = new Font("Arial", 10, FontStyle.Regular);
            pauseFont = new Font("Arial", 18, FontStyle.Bold);
            menuFont = new Font("Arial", 14, FontStyle.Regular);
            
            centerFormat = new StringFormat();
            centerFormat.Alignment = StringAlignment.Center;
            centerFormat.LineAlignment = StringAlignment.Center;
            
            objectsInitialized = true;
        }
        
        /// <summary>
        /// 初始化离屏渲染缓冲区
        /// </summary>
        private void InitializeOffscreenBuffer()
        {
            if (offscreenInitialized) return;
            
            // 创建离屏位图
            offscreenBitmap = new Bitmap(ScreenWidth, ScreenHeight);
            offscreenGraphics = Graphics.FromImage(offscreenBitmap);
            offscreenGraphics.SmoothingMode = SmoothingMode.AntiAlias;
            offscreenGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
            
            // 创建兼容DC和位图
            IntPtr screenDC = offscreenGraphics.GetHdc();
            offscreenDC = CreateCompatibleDC(screenDC);
            offscreenBitmapHandle = CreateCompatibleBitmap(screenDC, ScreenWidth, ScreenHeight);
            SelectObject(offscreenDC, offscreenBitmapHandle);
            offscreenGraphics.ReleaseHdc(screenDC);
            
            offscreenInitialized = true;
        }
        
        /// <summary>
        /// 初始化游戏
        /// </summary>
        private void InitializeGame()
        {
            // 创建玩家
            Player = new Player(ScreenWidth / 2 - 15, ScreenHeight / 2 - 15);
            
            // 创建游戏计时器 - 使用更高精度的定时器
            gameTimer = new Timer();
            gameTimer.Interval = 1; // 1ms 间隔，实现精确的60FPS
            gameTimer.Tick += GameLoop;
            
            lastUpdateTime = DateTime.Now;
            
            // 初始化离屏缓冲区
            InitializeOffscreenBuffer();
            
            // 初始化陨石对象池
            InitializeAsteroidPool();
        }
        
        /// <summary>
        /// 初始化陨石对象池
        /// </summary>
        private void InitializeAsteroidPool()
        {
            // 预创建陨石对象
            for (int i = 0; i < ASTEROID_POOL_SIZE; i++)
            {
                asteroidPool.Add(new Asteroid(0, 0, Asteroid.AsteroidSize.Medium, Asteroid.AsteroidSpeed.Medium, 0, 0));
            }
        }
        
        /// <summary>
        /// 从对象池获取陨石
        /// </summary>
        private Asteroid GetAsteroidFromPool()
        {
            if (asteroidPool.Count > 0)
            {
                Asteroid asteroid = asteroidPool[asteroidPool.Count - 1];
                asteroidPool.RemoveAt(asteroidPool.Count - 1);
                asteroid.IsActive = true;
                return asteroid;
            }
            
            // 如果池为空，创建新的陨石
            return new Asteroid(0, 0, Asteroid.AsteroidSize.Medium, Asteroid.AsteroidSpeed.Medium, 0, 0);
        }
        
        /// <summary>
        /// 将陨石返回到对象池
        /// </summary>
        private void ReturnAsteroidToPool(Asteroid asteroid)
        {
            if (asteroidPool.Count < ASTEROID_POOL_SIZE)
            {
                asteroid.IsActive = false;
                asteroidPool.Add(asteroid);
            }
        }
        
        /// <summary>
        /// 开始游戏
        /// </summary>
        public void StartGame()
        {
            // 重置游戏状态
            GameTime = 0;
            Difficulty = 0;
            asteroidSpawnTimer = 0;
            lastBossSpawnTime = 0;
            AsteroidsAvoided = 0;
            TotalEnemiesSpawned = 0;
            
            // 根据当前游戏模式设置参数
            var config = GameModeManager.CurrentConfig;
            asteroidSpawnInterval = config.InitialAsteroidSpawnInterval;
            
            // 清除所有陨石和粒子
            Asteroids.Clear();
            ParticleSystem.Clear();
            
            // 清理生成队列
            spawnQueue.Clear();
            
            // 重置玩家位置并设置速度倍数
            Player.Reset(ScreenWidth / 2 - 15, ScreenHeight / 2 - 15);
            Player.SetSpeedMultiplier(config.PlayerSpeedMultiplier);
            
            // 播放背景音乐
            SoundManager.PlayBackgroundMusic();
            
            // 开始游戏循环
            CurrentState = GameState.Playing;
            gameTimer.Start();
            lastUpdateTime = DateTime.Now;
            
            if (GameStateChanged != null) GameStateChanged(CurrentState);
        }
        
        /// <summary>
        /// 开始演示模式
        /// </summary>
        public void StartDemoMode()
        {
            // 重置演示模式状态
            IsDemoMode = true;
            demoModeTimer = 0;
            lastDemoDirectionChange = 0;
            demoModeDuration = GameSettings.Instance.DemoModeDuration;
            
            // 重置游戏状态
            GameTime = 0;
            Difficulty = 0;
            asteroidSpawnTimer = 0;
            lastBossSpawnTime = 0;
            AsteroidsAvoided = 0;
            TotalEnemiesSpawned = 0;
            
            // 根据当前游戏模式设置参数
            var config = GameModeManager.CurrentConfig;
            asteroidSpawnInterval = config.InitialAsteroidSpawnInterval;
            
            // 清除所有陨石和粒子
            Asteroids.Clear();
            ParticleSystem.Clear();
            
            // 清理生成队列
            spawnQueue.Clear();
            
            // 重置玩家位置并设置速度倍数
            Player.Reset(ScreenWidth / 2 - 15, ScreenHeight / 2 - 15);
            Player.SetSpeedMultiplier(config.PlayerSpeedMultiplier);
            
            // 播放背景音乐
            SoundManager.PlayBackgroundMusic();
            
            // 开始游戏循环
            CurrentState = GameState.Playing;
            gameTimer.Start();
            lastUpdateTime = DateTime.Now;
            
            if (GameStateChanged != null) GameStateChanged(CurrentState);
        }
        
        /// <summary>
        /// 停止演示模式
        /// </summary>
        public void StopDemoMode()
        {
            IsDemoMode = false;
            demoModeTimer = 0;
            
            // 重置玩家移动状态
            Player.MoveUp = false;
            Player.MoveDown = false;
            Player.MoveLeft = false;
            Player.MoveRight = false;
        }
        
        /// <summary>
        /// 暂停游戏
        /// </summary>
        public void PauseGame()
        {
            if (CurrentState == GameState.Playing)
            {
                CurrentState = GameState.Paused;
                gameTimer.Stop();
                if (GameStateChanged != null) GameStateChanged(CurrentState);
            }
        }
        
        /// <summary>
        /// 恢复游戏
        /// </summary>
        public void ResumeGame()
        {
            if (CurrentState == GameState.Paused)
            {
                CurrentState = GameState.Playing;
                gameTimer.Start();
                lastUpdateTime = DateTime.Now;
                if (GameStateChanged != null) GameStateChanged(CurrentState);
            }
        }
        
        /// <summary>
        /// 结束游戏
        /// </summary>
        public void EndGame()
        {
            CurrentState = GameState.GameOver;
            gameTimer.Stop();
            
            // 停止背景音乐
            SoundManager.StopBackgroundMusic();
            
            // 如果是演示模式，不记录成绩和成就
            if (!IsDemoMode)
            {
                // 增加游戏次数
                GamesPlayed++;
                
                // 更新成就进度
                AchievementSystem.UpdateProgress(AchievementType.TimeSurvived, GameTime);
                AchievementSystem.UpdateProgress(AchievementType.AsteroidsAvoided, AsteroidsAvoided);
                AchievementSystem.UpdateProgress(AchievementType.GamesPlayed, GamesPlayed);
                AchievementSystem.UpdateProgress(AchievementType.HighScore, GameTime);
                
                // 检查是否为新高分
                string modeName = GameModeManager.GetModeName(GameModeManager.CurrentMode);
                if (HighScoreManager.IsNewHighScore(GameTime, modeName))
                {
                    // 这里可以弹出输入框让玩家输入名字
                    HighScoreManager.AddHighScore("Player", GameTime, TotalEnemiesSpawned, modeName);
                }
                
                // 播放游戏结束音效
                SoundManager.PlaySoundEffect(SoundType.GameOver);
            }
            else
            {
                // 演示模式结束，停止演示模式
                StopDemoMode();
                
                // 如果启用了自动演示模式，自动重新开始演示
                if (GameSettings.Instance.AutoDemoMode)
                {
                    // 延迟一小段时间后重新开始演示
                    System.Threading.Timer restartTimer = null;
                    restartTimer = new System.Threading.Timer((obj) =>
                    {
                        if (CurrentState == GameState.GameOver)
                        {
                            // 通过事件通知UI线程重启演示模式
                            if (DemoRestartRequested != null) DemoRestartRequested();
                        }
                        restartTimer?.Dispose();
                    }, null, 1000, System.Threading.Timeout.Infinite);
                }
                else
                {
                    // 返回主菜单
                    ReturnToMenu();
                }
            }
            
            if (GameStateChanged != null) GameStateChanged(CurrentState);
            if (GameOver != null) GameOver();
        }
        
        /// <summary>
        /// 返回主菜单
        /// </summary>
        public void ReturnToMenu()
        {
            CurrentState = GameState.Menu;
            gameTimer.Stop();
            if (GameStateChanged != null) GameStateChanged(CurrentState);
        }
        
        /// <summary>
        /// 游戏主循环
        /// </summary>
        private void GameLoop(object sender, EventArgs e)
        {
            if (CurrentState != GameState.Playing) return;
            
            // 计算时间间隔
            DateTime currentTime = DateTime.Now;
            float deltaTime = (float)(currentTime - lastUpdateTime).TotalSeconds;
            lastUpdateTime = currentTime;
            
            // 限制最大帧时间，防止螺旋死亡
            if (deltaTime > MAX_FRAME_TIME)
                deltaTime = MAX_FRAME_TIME;
            
            // 性能监控
            frameCount++;
            frameTimer += deltaTime;
            averageFrameTime = deltaTime * 1000; // 转换为毫秒
            
            if (frameTimer >= FPS_UPDATE_INTERVAL)
            {
                currentFPS = frameCount / frameTimer;
                frameCount = 0;
                frameTimer = 0;
            }
            
            // 固定时间步长更新
            accumulator += deltaTime;
            
            while (accumulator >= FIXED_TIMESTEP)
            {
                // 更新游戏时间
                GameTime += FIXED_TIMESTEP;
                if (GameTimeUpdated != null) GameTimeUpdated(GameTime);
                
                // 检查游戏模式时间限制
                if (GameModeManager.ShouldEndGame(GameTime))
                {
                    EndGame();
                    return;
                }
                
                // 更新难度
                UpdateDifficulty();
                
                // 更新玩家
                Player.Update(FIXED_TIMESTEP);
                Player.CheckBounds(ScreenWidth, ScreenHeight);
                
                // 演示模式逻辑
                if (IsDemoMode)
                {
                    UpdateDemoMode(FIXED_TIMESTEP);
                }
                
                // 根据设置创建玩家尾迹效果（性能优化：减少创建频率）
                if ((Player.VelocityX != 0 || Player.VelocityY != 0) && GameSettings.Instance.ShowTrails)
                {
                    // 只在特定帧创建尾迹，减少粒子数量
                    if (frameCount % 3 == 0) // 每3帧创建一次
                    {
                        ParticleSystem.CreateTrail(Player.X + Player.Width / 2, Player.Y + Player.Height / 2, 
                            Player.VelocityX, Player.VelocityY);
                    }
                }
                
                // 更新陨石
                UpdateAsteroids(FIXED_TIMESTEP);
                
                // 生成新陨石
                UpdateAsteroidSpawner(FIXED_TIMESTEP);
                
                // 检测碰撞（性能优化：减少检测频率）
                if (frameCount % 2 == 0) // 每2帧检测一次
                {
                    CheckCollisions();
                }
                
                // 根据设置更新粒子系统
                if (GameSettings.Instance.ShowParticleEffects)
                {
                    ParticleSystem.Update(FIXED_TIMESTEP);
                }
                
                accumulator -= FIXED_TIMESTEP;
            }
            
            // 请求渲染
            if (RenderRequested != null)
            {
                RenderRequested();
            }
        }
        
        /// <summary>
        /// 更新难度
        /// </summary>
        private void UpdateDifficulty()
        {
            var config = GameModeManager.CurrentConfig;
            
            // 根据游戏模式配置计算难度
            Difficulty = Math.Min(GameTime * config.DifficultyIncreaseRate, config.MaxDifficulty);
            
            // 根据游戏模式配置调整陨石生成间隔
            asteroidSpawnInterval = GameModeManager.GetAsteroidSpawnInterval(GameTime);
        }
        
        /// <summary>
        /// 更新演示模式
        /// </summary>
        /// <param name="deltaTime">时间间隔</param>
        private void UpdateDemoMode(float deltaTime)
        {
            // 更新演示模式计时器
            demoModeTimer += deltaTime;
            
            // 检查演示模式是否结束
            if (demoModeTimer >= demoModeDuration)
            {
                EndGame();
                return;
            }
            
            // 更新方向改变计时器
            lastDemoDirectionChange += deltaTime;
            
            // 获取玩家中心位置
            float playerCenterX = Player.X + Player.Width / 2;
            float playerCenterY = Player.Y + Player.Height / 2;
            
            // 边界检测 - 如果接近边界，优先移动到安全区域
            float boundaryMargin = 50;
            bool nearBoundary = false;
            
            if (playerCenterX < boundaryMargin) // 接近左边界
            {
                Player.MoveRight = true;
                Player.MoveLeft = false;
                nearBoundary = true;
            }
            else if (playerCenterX > ScreenWidth - boundaryMargin) // 接近右边界
            {
                Player.MoveLeft = true;
                Player.MoveRight = false;
                nearBoundary = true;
            }
            
            if (playerCenterY < boundaryMargin) // 接近上边界
            {
                Player.MoveDown = true;
                Player.MoveUp = false;
                nearBoundary = true;
            }
            else if (playerCenterY > ScreenHeight - boundaryMargin) // 接近下边界
            {
                Player.MoveUp = true;
                Player.MoveDown = false;
                nearBoundary = true;
            }
            
            // 如果不在边界附近，进行智能避障
            if (!nearBoundary)
            {
                // 寻找最近的陨石
                Asteroid nearestAsteroid = FindNearestAsteroid();
                if (nearestAsteroid != null)
                {
                    float asteroidCenterX = nearestAsteroid.X + nearestAsteroid.Width / 2;
                    float asteroidCenterY = nearestAsteroid.Y + nearestAsteroid.Height / 2;
                    float distance = CalculateDistance(playerCenterX, playerCenterY, asteroidCenterX, asteroidCenterY);
                    
                    // 根据距离调整躲避策略
                    if (distance < 80) // 非常近，紧急躲避
                    {
                        // 计算躲避方向
                        float deltaX = playerCenterX - asteroidCenterX;
                        float deltaY = playerCenterY - asteroidCenterY;
                        
                        // 重置移动状态
                        Player.MoveUp = false;
                        Player.MoveDown = false;
                        Player.MoveLeft = false;
                        Player.MoveRight = false;
                        
                        // 优先躲避主要威胁方向
                        if (Math.Abs(deltaX) > Math.Abs(deltaY))
                        {
                            // 水平威胁更大
                            if (deltaX > 0) // 陨石在左侧
                                Player.MoveRight = true;
                            else // 陨石在右侧
                                Player.MoveLeft = true;
                        }
                        else
                        {
                            // 垂直威胁更大
                            if (deltaY > 0) // 陨石在上方
                                Player.MoveDown = true;
                            else // 陨石在下方
                                Player.MoveUp = true;
                        }
                    }
                    else if (distance < 150) // 中等距离，预测性躲避
                    {
                        // 预测陨石移动方向
                        float predictedX = asteroidCenterX + nearestAsteroid.VelocityX * 0.5f;
                        float predictedY = asteroidCenterY + nearestAsteroid.VelocityY * 0.5f;
                        
                        // 检查预测位置是否会对玩家造成威胁
                        float predictedDistance = CalculateDistance(playerCenterX, playerCenterY, predictedX, predictedY);
                        
                        if (predictedDistance < distance) // 陨石正在接近
                        {
                            // 计算最佳躲避方向
                            float safeX = playerCenterX + (playerCenterX - predictedX) * 0.5f;
                            float safeY = playerCenterY + (playerCenterY - predictedY) * 0.5f;
                            
                            // 确保安全位置在屏幕内
                            safeX = Math.Max(Player.Width / 2, Math.Min(ScreenWidth - Player.Width / 2, safeX));
                            safeY = Math.Max(Player.Height / 2, Math.Min(ScreenHeight - Player.Height / 2, safeY));
                            
                            // 重置移动状态
                            Player.MoveUp = false;
                            Player.MoveDown = false;
                            Player.MoveLeft = false;
                            Player.MoveRight = false;
                            
                            // 移动到安全位置
                            if (safeX > playerCenterX + 10)
                                Player.MoveRight = true;
                            else if (safeX < playerCenterX - 10)
                                Player.MoveLeft = true;
                            
                            if (safeY > playerCenterY + 10)
                                Player.MoveDown = true;
                            else if (safeY < playerCenterY - 10)
                                Player.MoveUp = true;
                        }
                    }
                }
                
                // 如果没有紧急情况，进行随机探索
                if (lastDemoDirectionChange >= demoDirectionChangeInterval)
                {
                    // 智能随机移动 - 避免移动到危险区域
                    List<int> safeDirections = new List<int>();
                    
                    // 检查各个方向的安全性
                    for (int i = 0; i < 9; i++)
                    {
                        if (IsDirectionSafe(i, playerCenterX, playerCenterY))
                        {
                            safeDirections.Add(i);
                        }
                    }
                    
                    // 如果没有安全方向，选择最安全的方向
                    if (safeDirections.Count == 0)
                    {
                        safeDirections.Add(0); // 静止
                    }
                    
                    // 从安全方向中随机选择
                    int direction = safeDirections[demoRandom.Next(safeDirections.Count)];
                    
                    // 重置所有移动状态
                    Player.MoveUp = false;
                    Player.MoveDown = false;
                    Player.MoveLeft = false;
                    Player.MoveRight = false;
                    
                    // 根据选择的方向设置移动状态
                    switch (direction)
                    {
                        case 0: // 静止
                            break;
                        case 1: // 上
                            Player.MoveUp = true;
                            break;
                        case 2: // 下
                            Player.MoveDown = true;
                            break;
                        case 3: // 左
                            Player.MoveLeft = true;
                            break;
                        case 4: // 右
                            Player.MoveRight = true;
                            break;
                        case 5: // 左上
                            Player.MoveUp = true;
                            Player.MoveLeft = true;
                            break;
                        case 6: // 右上
                            Player.MoveUp = true;
                            Player.MoveRight = true;
                            break;
                        case 7: // 左下
                            Player.MoveDown = true;
                            Player.MoveLeft = true;
                            break;
                        case 8: // 右下
                            Player.MoveDown = true;
                            Player.MoveRight = true;
                            break;
                    }
                    
                    lastDemoDirectionChange = 0;
                    
                    // 动态调整方向改变间隔 - 根据难度调整
                    float baseInterval = 0.5f;
                    float difficultyFactor = Math.Min(1.0f, GameTime / 60.0f); // 随时间增加难度
                    demoDirectionChangeInterval = baseInterval + (float)demoRandom.NextDouble() * (1.0f - difficultyFactor * 0.5f);
                }
            }
        }
        
        /// <summary>
        /// 检查指定方向是否安全
        /// </summary>
        /// <param name="direction">方向 (0-8)</param>
        /// <param name="playerX">玩家中心X坐标</param>
        /// <param name="playerY">玩家中心Y坐标</param>
        /// <returns>是否安全</returns>
        private bool IsDirectionSafe(int direction, float playerX, float playerY)
        {
            // 计算移动后的位置
            float moveDistance = 30; // 移动距离
            float newX = playerX;
            float newY = playerY;
            
            switch (direction)
            {
                case 0: // 静止
                    break;
                case 1: // 上
                    newY -= moveDistance;
                    break;
                case 2: // 下
                    newY += moveDistance;
                    break;
                case 3: // 左
                    newX -= moveDistance;
                    break;
                case 4: // 右
                    newX += moveDistance;
                    break;
                case 5: // 左上
                    newX -= moveDistance * 0.7f;
                    newY -= moveDistance * 0.7f;
                    break;
                case 6: // 右上
                    newX += moveDistance * 0.7f;
                    newY -= moveDistance * 0.7f;
                    break;
                case 7: // 左下
                    newX -= moveDistance * 0.7f;
                    newY += moveDistance * 0.7f;
                    break;
                case 8: // 右下
                    newX += moveDistance * 0.7f;
                    newY += moveDistance * 0.7f;
                    break;
            }
            
            // 检查是否在屏幕边界内
            if (newX < Player.Width / 2 || newX > ScreenWidth - Player.Width / 2 ||
                newY < Player.Height / 2 || newY > ScreenHeight - Player.Height / 2)
            {
                return false;
            }
            
            // 检查是否与陨石碰撞
            foreach (Asteroid asteroid in Asteroids)
            {
                float asteroidCenterX = asteroid.X + asteroid.Width / 2;
                float asteroidCenterY = asteroid.Y + asteroid.Height / 2;
                float distance = CalculateDistance(newX, newY, asteroidCenterX, asteroidCenterY);
                
                // 如果距离太近，认为不安全
                if (distance < 60)
                {
                    return false;
                }
            }
            
            return true;
        }
        
        /// <summary>
        /// 找到最近的陨石
        /// </summary>
        /// <returns>最近的陨石，如果没有则返回null</returns>
        private Asteroid FindNearestAsteroid()
        {
            Asteroid nearest = null;
            float minDistance = float.MaxValue;
            
            foreach (var asteroid in Asteroids)
            {
                float distance = CalculateDistance(Player.X + Player.Width / 2, Player.Y + Player.Height / 2,
                                                asteroid.X + asteroid.Width / 2, asteroid.Y + asteroid.Height / 2);
                if (distance < minDistance)
                {
                    minDistance = distance;
                    nearest = asteroid;
                }
            }
            
            return nearest;
        }
        
        /// <summary>
        /// 计算两点之间的距离
        /// </summary>
        /// <param name="x1">点1的X坐标</param>
        /// <param name="y1">点1的Y坐标</param>
        /// <param name="x2">点2的X坐标</param>
        /// <param name="y2">点2的Y坐标</param>
        /// <returns>两点之间的距离</returns>
        private float CalculateDistance(float x1, float y1, float x2, float y2)
        {
            float dx = x2 - x1;
            float dy = y2 - y1;
            return (float)Math.Sqrt(dx * dx + dy * dy);
        }
        
        /// <summary>
        /// 更新陨石
        /// </summary>
        /// <param name="deltaTime">时间间隔</param>
        private void UpdateAsteroids(float deltaTime)
        {
            for (int i = Asteroids.Count - 1; i >= 0; i--)
            {
                Asteroid asteroid = Asteroids[i];
                asteroid.Update(deltaTime);
                
                // 移除移出屏幕的陨石
                if (asteroid.IsOutOfBounds(ScreenWidth, ScreenHeight))
                {
                    Asteroids.RemoveAt(i);
                    AsteroidsAvoided++;
                    
                    // 创建星星效果
                    ParticleSystem.CreateStar(asteroid.X + asteroid.Width / 2, asteroid.Y + asteroid.Height / 2);
                    
                    // 将陨石返回到对象池
                    ReturnAsteroidToPool(asteroid);
                }
            }
        }
        
        /// <summary>
        /// 更新陨石生成器
        /// </summary>
        /// <param name="deltaTime">时间间隔</param>
        private void UpdateAsteroidSpawner(float deltaTime)
        {
            var config = GameModeManager.CurrentConfig;
            
            // 检查是否应该生成Boss陨石
            if (GameModeManager.ShouldSpawnBoss(GameTime, lastBossSpawnTime))
            {
                // 将Boss生成请求加入队列
                spawnQueue.Enqueue(new AsteroidSpawnRequest
                {
                    ScreenWidth = ScreenWidth,
                    ScreenHeight = ScreenHeight,
                    Difficulty = Difficulty,
                    IsBoss = true
                });
                
                lastBossSpawnTime = GameTime;
            }
            
            asteroidSpawnTimer += deltaTime;
            
            if (asteroidSpawnTimer >= asteroidSpawnInterval)
            {
                // 检查陨石数量限制
                int availableSlots = config.MaxAsteroids - Asteroids.Count;
                if (availableSlots > 0)
                {
                    // 计算本次要生成的陨石数量
                    int minSpawn = Math.Min(config.MinAsteroidsPerSpawn, availableSlots);
                    int maxSpawn = Math.Min(config.MaxAsteroidsPerSpawn, availableSlots);
                    
                    if (minSpawn > 0 && maxSpawn >= minSpawn)
                    {
                        // 将普通陨石生成请求加入队列
                        for (int i = 0; i < minSpawn; i++)
                        {
                            spawnQueue.Enqueue(new AsteroidSpawnRequest
                            {
                                ScreenWidth = ScreenWidth,
                                ScreenHeight = ScreenHeight,
                                Difficulty = Difficulty,
                                IsBoss = false
                            });
                        }
                    }
                }
                
                asteroidSpawnTimer = 0;
            }
            
            // 处理生成队列（分批生成）
            ProcessSpawnQueue();
        }
        
        /// <summary>
        /// 处理生成队列
        /// </summary>
        private void ProcessSpawnQueue()
        {
            int spawnsThisFrame = 0;
            
            while (spawnQueue.Count > 0 && spawnsThisFrame < MAX_SPAWNS_PER_FRAME)
            {
                var request = spawnQueue.Dequeue();
                
                if (request.IsBoss)
                {
                    // 生成Boss陨石
                    Asteroid bossAsteroid = GetAsteroidFromPool();
                    Asteroid.InitializeAsteroid(bossAsteroid, request.ScreenWidth, request.ScreenHeight, request.Difficulty);
                    bossAsteroid.Width = (int)(bossAsteroid.Width * 2.5f);
                    bossAsteroid.Height = (int)(bossAsteroid.Height * 2.5f);
                    bossAsteroid.VelocityX *= 0.7f;
                    bossAsteroid.VelocityY *= 0.7f;
                    Asteroids.Add(bossAsteroid);
                    TotalEnemiesSpawned++;
                    
                    // 播放Boss出现音效
                    SoundManager.PlaySoundEffect(SoundType.AsteroidHit);
                }
                else
                {
                    // 生成普通陨石
                    Asteroid asteroid = GetAsteroidFromPool();
                    Asteroid.InitializeAsteroid(asteroid, request.ScreenWidth, request.ScreenHeight, request.Difficulty);
                    Asteroids.Add(asteroid);
                    TotalEnemiesSpawned++;
                }
                
                spawnsThisFrame++;
            }
        }
        
        /// <summary>
        /// 检测碰撞（性能优化版本）
        /// </summary>
        private void CheckCollisions()
        {
            if (!Player.IsActive) return;
            
            // 性能优化：只检查在玩家附近的陨石
            float playerCenterX = Player.X + Player.Width / 2.0f;
            float playerCenterY = Player.Y + Player.Height / 2.0f;
            float checkRadius = Player.Width * 2.0f; // 检查半径
            
            foreach (Asteroid asteroid in Asteroids)
            {
                if (!asteroid.IsActive) continue;
                
                // 快速距离检查，避免不必要的精确碰撞检测
                float asteroidCenterX = asteroid.X + asteroid.Width / 2.0f;
                float asteroidCenterY = asteroid.Y + asteroid.Height / 2.0f;
                
                float distanceX = Math.Abs(playerCenterX - asteroidCenterX);
                float distanceY = Math.Abs(playerCenterY - asteroidCenterY);
                
                // 如果距离太远，跳过精确碰撞检测
                if (distanceX > checkRadius || distanceY > checkRadius) continue;
                
                // 进行精确碰撞检测
                if (Player.CollidesWith(asteroid))
                {
                    // 创建爆炸效果
                    ParticleSystem.CreateExplosion(Player.X + Player.Width / 2, Player.Y + Player.Height / 2, 2.0f);
                    
                    // 播放爆炸音效
                    SoundManager.PlaySoundEffect(SoundType.Explosion);
                    
                    // 发生碰撞，游戏结束
                    EndGame();
                    return;
                }
            }
        }
        
        /// <summary>
        /// 渲染游戏（简化测试版本）
        /// </summary>
        /// <param name="g">绘图对象</param>
        public void Render(Graphics g)
        {
            // 清除背景
            g.Clear(Color.Black);
            
            // 初始化缓存对象
            if (!objectsInitialized) InitializeCachedObjects();
            
            // 绘制星空背景
            DrawStarfield(g);
            
            // 根据游戏状态绘制不同内容
            switch (CurrentState)
            {
                case GameState.Menu:
                    DrawMenu(g);
                    break;
                    
                case GameState.Playing:
                    DrawGame(g);
                    break;
                    
                case GameState.Paused:
                    DrawGame(g);
                    DrawPauseOverlay(g);
                    break;
                    
                case GameState.GameOver:
                    DrawGameOver(g);
                    break;
            }
        }
        
        /// <summary>
        /// 绘制星空背景
        /// </summary>
        /// <param name="g">绘图对象</param>
        private void DrawStarfield(Graphics g)
        {
            // 性能优化：缓存星空位置
            if (!starfieldInitialized)
            {
                InitializeStarfield();
            }
            
            // 使用缓存的画笔绘制星星
            using (SolidBrush starBrush = new SolidBrush(Color.White))
            {
                for (int i = 0; i < starPositions.Length; i++)
                {
                    Point pos = starPositions[i];
                    int size = starSizes[i];
                    g.FillEllipse(starBrush, pos.X, pos.Y, size, size);
                }
            }
        }
        
        /// <summary>
        /// 初始化星空背景缓存
        /// </summary>
        private void InitializeStarfield()
        {
            Random rand = new Random(123); // 固定种子，保持星星位置不变
            starPositions = new Point[100];
            starSizes = new int[100];
            
            for (int i = 0; i < 100; i++)
            {
                starPositions[i] = new Point(rand.Next(ScreenWidth), rand.Next(ScreenHeight));
                starSizes[i] = rand.Next(1, 3);
            }
            
            starfieldInitialized = true;
        }
        
        /// <summary>
        /// 重置星空背景缓存（当屏幕尺寸改变时调用）
        /// </summary>
        public void ResetStarfieldCache()
        {
            starfieldInitialized = false;
        }
        
        /// <summary>
        /// 重置离屏缓冲区（当屏幕尺寸改变时调用）
        /// </summary>
        public void ResetOffscreenBuffer()
        {
            // 释放旧的离屏缓冲区资源
            if (offscreenInitialized)
            {
                if (offscreenGraphics != null)
                {
                    offscreenGraphics.Dispose();
                    offscreenGraphics = null;
                }
                
                if (offscreenBitmap != null)
                {
                    offscreenBitmap.Dispose();
                    offscreenBitmap = null;
                }
                
                if (offscreenBitmapHandle != IntPtr.Zero)
                {
                    DeleteObject(offscreenBitmapHandle);
                    offscreenBitmapHandle = IntPtr.Zero;
                }
                
                if (offscreenDC != IntPtr.Zero)
                {
                    DeleteDC(offscreenDC);
                    offscreenDC = IntPtr.Zero;
                }
                
                offscreenInitialized = false;
            }
            
            // 重新初始化离屏缓冲区
            InitializeOffscreenBuffer();
        }
        
        /// <summary>
        /// 绘制主菜单（性能优化版本）
        /// </summary>
        /// <param name="g">绘图对象</param>
        private void DrawMenu(Graphics g)
        {
            if (!objectsInitialized) InitializeCachedObjects();
            
            // 绘制标题
            string title = "星际躲避";
            SizeF titleSize = g.MeasureString(title, titleFont);
            float titleX = (ScreenWidth - titleSize.Width) / 2;
            float titleY = ScreenHeight / 3;
            g.DrawString(title, titleFont, whiteBrush, titleX, titleY);
            
            // 绘制菜单选项
            string[] menuItems = {
                "按空格键开始游戏",
                "使用方向键控制飞船",
                "躲避陨石，生存更久！",
                "按Ctrl+D开始演示模式"
            };
            
            float menuY = titleY + titleSize.Height + 50;
            foreach (string item in menuItems)
            {
                SizeF itemSize = g.MeasureString(item, menuFont);
                float itemX = (ScreenWidth - itemSize.Width) / 2;
                g.DrawString(item, menuFont, whiteBrush, itemX, menuY);
                menuY += itemSize.Height + 10;
            }
        }
        
        /// <summary>
        /// 绘制游戏画面
        /// </summary>
        /// <param name="g">绘图对象</param>
        private void DrawGame(Graphics g)
        {
            // 绘制玩家
            Player.Draw(g);
            
            // 性能优化：批量绘制陨石
            // 首先筛选可见的陨石
            List<Asteroid> visibleAsteroids = new List<Asteroid>();
            foreach (Asteroid asteroid in Asteroids)
            {
                if (asteroid.IsVisible(ScreenWidth, ScreenHeight))
                {
                    visibleAsteroids.Add(asteroid);
                }
            }
            
            // 批量绘制可见的陨石
            if (visibleAsteroids.Count > 0)
            {
                Asteroid.DrawBatch(g, visibleAsteroids);
            }
            
            // 绘制UI
            DrawGameUI(g);
            
            // 如果游戏暂停，绘制暂停提示
            if (CurrentState == GameState.Paused)
            {
                DrawPauseOverlay(g);
            }
        }
        
        /// <summary>
        /// 绘制游戏UI（性能优化版本）
        /// </summary>
        /// <param name="g">绘图对象</param>
        private void DrawGameUI(Graphics g)
        {
            // 使用缓存的字体和画笔
            if (!objectsInitialized) InitializeCachedObjects();
            
            // 预分配字符串缓冲区以减少GC压力
            string timeText = $"时间: {GameTime:F1}秒";
            string difficultyText = $"难度: {Difficulty:F2}";
            string avoidedText = $"躲避陨石: {AsteroidsAvoided}";
            string enemiesText = $"敌人: {TotalEnemiesSpawned}";
            
            // 绘制基本信息
            g.DrawString(timeText, uiFont, whiteBrush, 10, 10);
            g.DrawString(difficultyText, uiFont, whiteBrush, 10, 30);
            g.DrawString(avoidedText, uiFont, whiteBrush, 10, 50);
            g.DrawString(enemiesText, uiFont, whiteBrush, 10, 90);
            
            // 绘制演示模式信息
            if (IsDemoMode)
            {
                float remainingDemoTime = demoModeDuration - demoModeTimer;
                string demoText = $"演示模式: {remainingDemoTime:F1}秒";
                g.DrawString(demoText, uiFont, yellowBrush, 10, 110);
            }
            
            // 绘制剩余时间（如果适用）
            if (GameModeManager.CurrentConfig.TimeLimit > 0)
            {
                float remainingTime = GameModeManager.CurrentConfig.TimeLimit - GameTime;
                if (remainingTime > 0)
                {
                    string remainingText = $"剩余时间: {remainingTime:F1}秒";
                    g.DrawString(remainingText, uiFont, whiteBrush, 10, 70);
                }
            }
            
            // 性能监控：显示FPS和粒子数量（仅在调试模式下或FPS较低时显示）
            if (currentFPS < 30 || GameSettings.Instance.ShowFPS)
            {
                string fpsText = $"FPS: {currentFPS:F1} ({averageFrameTime:F1}ms)";
                SolidBrush fpsBrush = currentFPS < 30 ? redBrush : yellowBrush;
                g.DrawString(fpsText, uiFont, fpsBrush, ScreenWidth - 150, 10);
                
                // 显示粒子数量信息
                string particleText = $"粒子: {ParticleSystem.ActiveParticleCount}/{ParticleSystem.TotalParticleCount}";
                g.DrawString(particleText, uiFont, whiteBrush, ScreenWidth - 150, 30);
            }
        }
        
        /// <summary>
        /// 绘制暂停覆盖层（性能优化版本）
        /// </summary>
        /// <param name="g">绘图对象</param>
        private void DrawPauseOverlay(Graphics g)
        {
            if (!objectsInitialized) InitializeCachedObjects();
            
            // 半透明背景
            using (SolidBrush overlayBrush = new SolidBrush(Color.FromArgb(128, 0, 0, 0)))
            {
                g.FillRectangle(overlayBrush, 0, 0, ScreenWidth, ScreenHeight);
            }
            
            // 暂停文本
            string pauseText = "游戏暂停";
            SizeF pauseSize = g.MeasureString(pauseText, pauseFont);
            float pauseX = (ScreenWidth - pauseSize.Width) / 2;
            float pauseY = (ScreenHeight - pauseSize.Height) / 2;
            g.DrawString(pauseText, pauseFont, whiteBrush, pauseX, pauseY);
        }
        
        /// <summary>
        /// 绘制游戏结束画面（性能优化版本）
        /// </summary>
        /// <param name="g">绘图对象</param>
        private void DrawGameOver(Graphics g)
        {
            if (!objectsInitialized) InitializeCachedObjects();
            
            // 绘制游戏画面（背景）
            DrawGame(g);
            
            // 半透明覆盖层
            using (SolidBrush overlayBrush = new SolidBrush(Color.FromArgb(180, 0, 0, 0)))
            {
                g.FillRectangle(overlayBrush, 0, 0, ScreenWidth, ScreenHeight);
            }
            
            // 游戏结束标题
            string gameOverText = "游戏结束";
            SizeF titleSize = g.MeasureString(gameOverText, titleFont);
            float titleX = (ScreenWidth - titleSize.Width) / 2;
            float titleY = ScreenHeight / 4;
            g.DrawString(gameOverText, titleFont, whiteBrush, titleX, titleY);
            
            // 预格式化字符串以减少GC压力
            string timeText = $"生存时间: {GameTime:F1}秒";
            string avoidedText = $"躲避陨石: {AsteroidsAvoided}个";
            string enemiesText = $"敌人总数: {TotalEnemiesSpawned}个";
            string modeText = $"游戏模式: {GameModeManager.CurrentConfig.Name}";
            string restartText = "按空格键重新开始";
            string menuText = "按ESC键返回菜单";
            
            // 绘制信息
            SizeF timeSize = g.MeasureString(timeText, infoFont);
            float timeX = (ScreenWidth - timeSize.Width) / 2;
            float timeY = titleY + titleSize.Height + 20;
            g.DrawString(timeText, infoFont, whiteBrush, timeX, timeY);
            
            SizeF avoidedSize = g.MeasureString(avoidedText, infoFont);
            float avoidedX = (ScreenWidth - avoidedSize.Width) / 2;
            float avoidedY = timeY + timeSize.Height + 10;
            g.DrawString(avoidedText, infoFont, whiteBrush, avoidedX, avoidedY);
            
            SizeF enemiesSize = g.MeasureString(enemiesText, infoFont);
            float enemiesX = (ScreenWidth - enemiesSize.Width) / 2;
            float enemiesY = avoidedY + avoidedSize.Height + 10;
            g.DrawString(enemiesText, infoFont, whiteBrush, enemiesX, enemiesY);
            
            SizeF modeSize = g.MeasureString(modeText, infoFont);
            float modeX = (ScreenWidth - modeSize.Width) / 2;
            float modeY = enemiesY + enemiesSize.Height + 10;
            g.DrawString(modeText, infoFont, whiteBrush, modeX, modeY);
            
            SizeF restartSize = g.MeasureString(restartText, infoFont);
            float restartX = (ScreenWidth - restartSize.Width) / 2;
            float restartY = modeY + modeSize.Height + 20;
            g.DrawString(restartText, infoFont, whiteBrush, restartX, restartY);
            
            SizeF menuSize = g.MeasureString(menuText, infoFont);
            float menuX = (ScreenWidth - menuSize.Width) / 2;
            float menuY = restartY + restartSize.Height + 10;
            g.DrawString(menuText, infoFont, whiteBrush, menuX, menuY);
        }
        
        /// <summary>
        /// 处理键盘输入
        /// </summary>
        /// <param name="keyCode">按键代码</param>
        /// <param name="isKeyDown">是否按下</param>
        public void HandleKeyInput(Keys keyCode, bool isKeyDown)
        {
            switch (CurrentState)
            {
                case GameState.Menu:
                    if (isKeyDown && keyCode == Keys.Space)
                    {
                        StartGame();
                    }
                    else if (isKeyDown && keyCode == Keys.D && (Control.ModifierKeys & Keys.Control) != 0)
                    {
                        StartDemoMode();
                    }
                    break;
                    
                case GameState.Playing:
                    HandleGameInput(keyCode, isKeyDown);
                    break;
                    
                case GameState.Paused:
                    if (isKeyDown && keyCode == Keys.Escape)
                    {
                        ResumeGame();
                    }
                    break;
                    
                case GameState.GameOver:
                    if (isKeyDown && keyCode == Keys.Space)
                    {
                        StartGame();
                    }
                    else if (isKeyDown && keyCode == Keys.Escape)
                    {
                        ReturnToMenu();
                    }
                    break;
            }
        }
        
        /// <summary>
        /// 处理游戏中的输入
        /// </summary>
        /// <param name="keyCode">按键代码</param>
        /// <param name="isKeyDown">是否按下</param>
        private void HandleGameInput(Keys keyCode, bool isKeyDown)
        {
            switch (keyCode)
            {
                case Keys.Up:
                case Keys.W:
                    Player.MoveUp = isKeyDown;
                    break;
                    
                case Keys.Down:
                case Keys.S:
                    Player.MoveDown = isKeyDown;
                    break;
                    
                case Keys.Left:
                case Keys.A:
                    Player.MoveLeft = isKeyDown;
                    break;
                    
                case Keys.Right:
                case Keys.D:
                    Player.MoveRight = isKeyDown;
                    break;
                    
                case Keys.Escape:
                    if (isKeyDown)
                    {
                        PauseGame();
                    }
                    break;
            }
        }
        
        /// <summary>
        /// 成就解锁事件处理
        /// </summary>
        /// <param name="achievement">解锁的成就</param>
        private void OnAchievementUnlocked(Achievement achievement)
        {
            // 播放成就解锁音效
            SoundManager.PlaySoundEffect(SoundType.PowerUp);
            
            // 触发成就解锁事件
            if (AchievementUnlocked != null)
            {
                AchievementUnlocked(achievement);
            }
        }
        
        /// <summary>
        /// 释放资源
        /// </summary>
        public void Dispose()
        {
            // 停止游戏计时器
            if (gameTimer != null)
            {
                gameTimer.Stop();
                gameTimer.Dispose();
                gameTimer = null;
            }
            
            // 释放系统资源
            if (SoundManager != null)
            {
                SoundManager.Dispose();
                SoundManager = null;
            }
            

            
            // 释放离屏缓冲区资源
            if (offscreenInitialized)
            {
                if (offscreenGraphics != null)
                {
                    offscreenGraphics.Dispose();
                    offscreenGraphics = null;
                }
                
                if (offscreenBitmap != null)
                {
                    offscreenBitmap.Dispose();
                    offscreenBitmap = null;
                }
                
                if (offscreenBitmapHandle != IntPtr.Zero)
                {
                    DeleteObject(offscreenBitmapHandle);
                    offscreenBitmapHandle = IntPtr.Zero;
                }
                
                if (offscreenDC != IntPtr.Zero)
                {
                    DeleteDC(offscreenDC);
                    offscreenDC = IntPtr.Zero;
                }
                
                offscreenInitialized = false;
            }
            
            // 释放缓存的绘图对象
            DisposeCachedObjects();
        }
        
        /// <summary>
        /// 释放缓存的对象
        /// </summary>
        private void DisposeCachedObjects()
        {
            if (!objectsInitialized) return;
            
            // 释放画笔
            whiteBrush?.Dispose();
            blackBrush?.Dispose();
            redBrush?.Dispose();
            yellowBrush?.Dispose();
            
            // 释放字体
            uiFont?.Dispose();
            titleFont?.Dispose();
            infoFont?.Dispose();
            pauseFont?.Dispose();
            menuFont?.Dispose();
            
            // 释放字符串格式
            centerFormat?.Dispose();
            
            // 重置标志
            objectsInitialized = false;
        }
    }
} 